package com.example.bdd.demo.pages;

import com.example.bdd.demo.base.BddBaseService;
import com.example.bdd.demo.enu.Page;
import com.example.bdd.demo.model.BddAutoFillData;
import com.example.bdd.demo.utils.FileUtil;
import org.openqa.selenium.By;

import java.util.Map;
import java.util.TreeMap;

public class CommonPageService {

    private BddBaseService bddBaseService;
    private IndexPageService indexPageService;
    private Page1Service page1Service;
    private Page2Service page2Service;
    private Map<Integer,Object> pageServiceMap;

    public CommonPageService(BddBaseService bddBaseService){
        this.bddBaseService = bddBaseService;
        this.indexPageService = new IndexPageService(bddBaseService);
        this.page1Service = new Page1Service(bddBaseService);
        this.page2Service = new Page2Service(bddBaseService);
        this.pageServiceMap = new TreeMap<>();
        pageServiceMap.put(1, indexPageService);
        pageServiceMap.put(2, page1Service);
        pageServiceMap.put(3, page2Service);
    }

    public void load(String domain){
        bddBaseService.load(domain);
    }

    public void jumpToPage(String page){
        String readFile = FileUtil.readFile("src\\test\\resources\\static\\bdd-data.json");
        BddAutoFillData bddAutoFillData = FileUtil.convert(readFile, BddAutoFillData.class);
        int pageNum = Page.getPageNumByPageName(page);
        for (Map.Entry<Integer,Object> entry : pageServiceMap.entrySet()) {
            Object obj = entry.getValue();
            if (pageNum == 1 && entry.getKey() == pageNum) {
                ((IndexPageService) obj).setFields(bddAutoFillData);
            }
            if (pageNum > 1 && entry.getKey() < pageNum) {
                if (obj instanceof IndexPageService) {
                    ((IndexPageService) obj).setFields(bddAutoFillData);
                    clickNextButton();
                } else if (obj instanceof Page1Service) {
                    ((Page1Service) obj).setFields(bddAutoFillData);
                    clickNextButton();
                } else if (obj instanceof Page2Service) {
                    ((Page2Service) obj).setFields(bddAutoFillData);
                    clickNextButton();
                }
            }
        }
    }

    public String getPageTitle() {
        return bddBaseService.getFieldValue(By.id("pageTitle"));
    }

    public boolean checkPageTitle(String title) {
        return getPageTitle().equals(title);
    }

    public void selectRadio(String name, int index) {
        bddBaseService.selectRadio(By.name(name), index);
    }

    public boolean clickNextButton() {
        bddBaseService.clickButton(By.id("nextPageButton"));
        return true;
    }

    public void closePage(boolean isAfterScenario) {
        bddBaseService.closePage(isAfterScenario);
    }
}
